﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.IO;
using Microsoft.SPOT.Net.NetworkInformation;

using WebServer;
using SDCard;

// todo fix cache control headers
// binary upload
// check  socket exceptions coming out of listen to see if cleanup is done properly
// global for total exception count
// organise globals maybe

public class Program
{
    private static IndexPage _IndexPage = null;
    private static UploadPage _UploadPage = null;
    private static UploadForm _UploadForm = null;

    public static float[] temperaturesInCelsius;// todo do these need to be static?
    public static SDCard.SDCard _SDCard = null;
    public static A2D _A2D = null;

    public static void Main()
    {
//        //OutputPort SdPower = new OutputPort((Cpu.Pin)25, false); // ensure that the SD card is powered
//        //Thread.Sleep(1000);
//        //InputPort sdDetected = new InputPort((Cpu.Pin)57, false, Port.ResistorMode.PullUp);
//        //ConsoleWrite.Print("sd detected: " + (!sdDetected.Read()).ToString());
//        //sdDetected.Dispose();
//        bool reboot = false;
//        ConsoleWrite.Print("Current directory (before): " + Directory.GetCurrentDirectory());
//        try
//        {
//            string[] rootDirs = System.IO.Directory.GetDirectories("\\");

//            string[] rootDirs2 = System.IO.Directory.GetDirectories("\\SD");
 
// //           Directory.SetCurrentDirectory("\\");
// //           Directory.SetCurrentDirectory("\\Netduino\\");
//        }
//        catch(Exception ex)
//        {

//            ConsoleWrite.Print("Exception occurred while calling SetCurrentDirectory: " + ex.Message);
////            reboot = true;

//        }
//        if (reboot)
//        {
//            PowerState.RebootDevice(true);
//        }
//        ConsoleWrite.Print("Current directory (after): " + Directory.GetCurrentDirectory());



        //only use if mac gets reset by enabledhcp() call
        //var ni = NetworkInterface.GetAllNetworkInterfaces()[0];
        //if (ni.PhysicalAddress[0] == 0x00)
        //{
        //    ConsoleWrite.Print("Restoring Physical Address...");
        //    ni.PhysicalAddress = new byte[] { 0x5C, 0x86, 0x4A, 0x , 0x , 0x  };// put in actual supplied mac
        //   // ConsoleWrite.Print("MAC Address: " + ni.PhysicalAddress.ToHexString());
        //} 
        Debug.EnableGCMessages(true);        
        _SDCard = new SDCard.SDCard();
        _IndexPage = new IndexPage();
        _UploadPage = new UploadPage();
        _UploadForm = new UploadForm();
        WebServer.WebServer server = new WebServer.WebServer(80, _SDCard);
        // Add a handler for commands that are received by the server.
        server.ResponseHandler += new WebServer.ResponseHandler(server_CommandReceived);
        server.Start();
        // comment if memory short doesn't work
//        BoolDelegate pauseA2DDelegate = new BoolDelegate();
        _A2D = new A2D();
        temperaturesInCelsius = new float[A2D.InputCount];
        _A2D.MainLoop(temperaturesInCelsius);
    }


    /// <summary>
    /// Handles the CommandReceived event.
    /// </summary>
    private static string server_CommandReceived(BaseRequest request)
    {
        string result = "";
        try
        {
            // todo refactor as switch
            if (request.BaseUri.ToUpper().IndexOf("UPLOADPAGE") >= 0) //case insensitive
            {
                _A2D.PauseThread(true);
                result = _UploadPage.DoUploadPage(request, _SDCard);
            }
            else
            {
                if (request.BaseUri.ToUpper().IndexOf("UPLOADFORM") >= 0) //case insensitive
                {
                    result = _UploadForm.DoUploadForm(request, _SDCard);
                }
                else
                { // other pages go here
                    result = _IndexPage.GetIndexPage(request, temperaturesInCelsius, _SDCard);
                }
            }
        }
        catch (Exception ex)
        {
            string content = HtmlGeneral.HtmlStart + "<h1>500 server error.</h1>" + "<h3>Uri: " + request.Uri + "</h3>";
            content += "<p>Error: " + ex.Message + "</p>" + HtmlGeneral.HtmlEnd;
            string header = HttpGeneral.Get500Header(content.Length);
            result = header + content;
        }
        finally
        {
            _A2D.PauseThread(false);// always let it run// assumes only one upload happening at a time. 2 would kill it anyway.
        }
        return result;

        //led control implementation
        //return (new LedAction(Hardware.Led)).Action(request);
    }

}

